<template>
	<div :style="{
		display: 'flex',
		flex: 1,
		flexBasis: 'auto',
		flexDirection: 'column',
	}">
		<Matchheader v-bind="{
			time, submit, title: match ? match.name : '',
			save, savetime, saveloading, match, isMatch
		}">
		</Matchheader>
		<Question ref="ques" v-if="question && question.type === '代码'" v-bind="{
			question,
			questionlist: list,
			index: Number(index),
			setuserdata,
			userdata,
			match,

		}">
			<Matchfooter v-bind="{
				index: Number(index), questionlist: list, userquestion: matchuser?.userquestion
					|| []
			}"></Matchfooter>
		</Question>
		<questionselect ref="select" v-if="question && question.type !== '代码'" v-bind="{
			question,
			questionlist: list,
			index: Number(index),
			setuserdata,
			userdata,
		}">
			<Matchfooter v-bind="{ index: Number(index), questionlist: list }"></Matchfooter>
		</questionselect>
	</div>
</template>

<script setup lang="ts">

import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { Socket } from "socket.io-client";
import { assign } from "underscore";
import {
	computed,
	onMounted,
	reactive,
	ref,
	toRefs,
	watch
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
	Apimatchuserquestion,
	asyncgettmpmatchuserdata,
	asyncsavetmpmatchuserdata,
	asyncselectmatchquestion,
	jilurizhi,
} from "../../../api";
import { Storekey } from "../../../interface";
import { IWsEmitatactivity } from "../../../mysql_interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { markdownhtml } from "../../../util/htmlstring";
import { SMP } from "./interface";
import Matchfooter from "./matchfooter.vue";
import Matchheader from "./matchheader.vue";
import Question from "./question.vue";
import questionselect from "./questionselect.vue";

const p = defineProps<{
	index: string
	match: SMP["match"],
	time: SMP["time"],
	matchuser?: Apimatchuserquestion,
	start: Function,
	isnot: { err: number; msg: string }
	setresult: Function,
	sub: Boolean,
}>()

const { index, isnot, matchuser } = toRefs(p);
const isMatch = true

const list = ref<Studycodemodel.Imatchquestion[]>([]);
const store = useStore(Storekey);

const router = useRouter();
const user = computed<Studycodemodel.Iuser>(() => {
	return store.getters.getuser;
});

const ques = ref<typeof Question>();
const select = ref<typeof questionselect>();

const userdata = reactive<Record<string, any>>({});
const question = computed(() => {
	const n = list.value[Number(index.value)]
	if (n) {
		return markdownhtml(n) as Studycodemodel.Imatchquestion
	}
	return null
});
function setuserdata(key: string, context: any) {
	console.log("缓存代码：", context)
	userdata[key] = context;
}

const savetime = ref()
const saveloading = ref(false)

watch(userdata, () => {
	if (!p.match.ID) {
		return;
	}
	saveloading.value = true
	asyncsavetmpmatchuserdata({
		activityid: p.match.ID,
		data: userdata,
		seconds: 1000 * 60 * 60 * 24,
	}).then((e) => {
		saveloading.value = false
		savetime.value = moment().format('HH:mm:ss')
		const t: IWsEmitatactivity = "atactivity";
		store.state.socket.emit(t, {
			activityid: p.match.ID,
			userid: store.state.user?.ID,
		});
	});
});

watch(
	() => index.value,
	() => {
		if (Number(p.index) > list.value.length) {
			router.push({
				name: "比赛答题",
				params: {
					index: 0,
				},
			});
		}
	}
);

watch(
	() => p.sub,
	() => {
		if (user.value) {
			submit();
		}
	}
);
const hanzi = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百']

function save() {
	if (!p.match.ID) {
		return;
	}

	if (ques.value?.context) {
		if (ques.value.context && question.value?.ID) {
			userdata[question.value.ID] = assign({}, userdata[question.value.ID], {
				context: ques.value.context,
				language: ques.value.language || "CPP",
				gccoptimize: ques.value.gccoptimize
			})
		}
	}
}

function submit(b = true) {
	if (!p.match.ID) {
		return;
	}
	if (ques.value) {
		if (ques.value.context && question.value?.ID) {
			userdata[question.value.ID] = {
				context: ques.value.context,
				language: ques.value.language || "CPP",
				gccoptimize: ques.value.gccoptimize
			};
		}
	}
	const socket: Socket =
		store.state.socket;
	const t = list.value.map((v) => {
		const obj: Studycodemodel.Imatchuserquestion = {};
		if (v.ID) {
			const context = userdata[v.ID];

			obj.type = v.type;
			obj.questionid = v.ID;
			obj.info = {};
			if (v.type !== "代码") {
				obj.questionid;
				obj.info.answer = context;
			} else {
				obj.language = context?.language;
				obj.context = context?.context;
				obj.gccoptimize = context?.gccoptimize ? '-O2' : undefined;
				// 比赛的运行测试和提交代码 需要加上是否文件读写
				obj.isfile = p.match.isfile || false;
			}
			return obj;
		}
		return {};
	});
	if (!b) {
		socket.emit("match", {
			activityid: p.match.ID,
			data: [t[Number(index.value)]],
			userid: user.value.ID,
		});
		return '只提交当前题目'
	}

	// 如果强制提交
	if (p.sub && socket) {
		socket.emit("match", {
			activityid: p.match.ID,
			data: t,
			userid: user.value.ID,
		});
		router.push({ name: "比赛结束" });
		return;
	}
	ElMessageBox.confirm("是否要提交此次比赛所有题目答题？提交试卷后即结束本次比赛，无法再次进入比赛", "提交")
		.then(() => {
			if (!p.match.ID) {
				return;
			}
			console.log(t)
			socket.emit("match", {
				activityid: p.match.ID,
				data: t,
				userid: user.value.ID,
			});
			const arr: [string, any][] = [];

			arr[0] = ["_method_", "match"];
			arr[1] = ["type", "scoket"];
			arr[2] = ["ismatch", true];
			arr[3] = ["matchid", p.match.ID];
			arr[4] = ["matchname", p.match.name];
			jilurizhi(arr);
			router.push({ name: "比赛结束" });
		})
		.catch((e: any) => {
			ElMessage.error(e);
		});
}

async function Mounted() {
	await p.start();
	if (!user.value) {
		ElMessage.error("请登录");
		router.push("/");
	}
	if (!p.match?.ID) {
		router.push("/");
		return;
	}
	if (p.match) {
		const d = p.match.activityuser?.find((v) => v.ID == user.value.ID);
		if (d) {
			ElMessage.error("没有报名");
			router.push("/");
		}
	}
	if (isnot.value.err) {
		ElMessage.error(isnot.value.msg);
		router.push("/");
	}
	const [data] = await asyncselectmatchquestion({ activityid: p.match.ID, });
	if (data) {
		list.value =
			data.matchquestion?.sort((a, b) => Number(a.paixu) - Number(b.paixu)).map((f, k) => {
				if (!p.match.isshowquestionname) {
					return {
						...f,
						name: `第${k + 1}题`
					}
				}
				return f
			}) || [];
	}
	if (list.value.length === 0) {
		ElMessage.error("此次比赛已结束");
		router.push("/");
	}
	asyncgettmpmatchuserdata({
		activityid: p.match.ID,
	})
		.then((olddata = {}) => {
			Object.assign(userdata, olddata);
			// 缓存数据获取
			let id;
			if (question.value?.ID) {
				const data = (olddata as any)[question.value.ID];
				if (data) {
					id = data;
				}
			}
			if (ques.value) {
				if (!ques.value.context) {
					ques.value.context = id?.context;
					ques.value.language = id?.language || "CPP";
					// console.log("同步缓存", id, id?.gccoptimize)
					// 为什么gccoptimize是  缓存没有才勾上 有就不勾选
					// ques.value.gccoptimize = id?.gccoptimize === undefined ? true : false
					ques.value.gccoptimize = id?.gccoptimize ? true : false
				}
			}
			if (select.value) {
				if (!select.value.data) {
					select.value.data = id;
				}
			}
		})
		.catch((e) => {
			console.log(e);
		});
}

onMounted(() => {
	Mounted();
});



</script>
